package com.bigknow.appstore.web.base.controller;

import com.bigknow.appstore.web.base.entity.User;
import com.bigknow.appstore.web.base.service.IUserService;
import com.bigknow.appstore.web.framework.controller.AbstractRestController;
import com.bigknow.appstore.web.framework.vo.ResultInfo;
import com.bigknow.appstore.web.framework.vo.VoFactory;
import org.mongodb.morphia.Datastore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import static com.bigknow.appstore.web.framework.util.GlobalConstant.UPDATE_NONE;
import static com.bigknow.appstore.web.framework.util.GlobalConstant.UPDATE_SUCCESS;

/**
 * Created by chaos on 2016/6/20.
 */
@RestController
@RequestMapping(value = "/DVConsole/user")
public class DVConsoleUserController extends AbstractRestController<User, IUserService> {
    @Override
    protected String getBasePath() {
        return "/DVConsole";
    }

    @Autowired
    private Datastore ds;

    @RequestMapping(value = "/userFormForIndexEdit")
    public ModelAndView formPage(String userId, Model model){
        if(userId!=null){
            User user = ds.find(User.class).field("id").equal(userId).get();
            model.addAttribute("user",user);
        }
        return new ModelAndView("/base/user/userFormForIndexEdit",model.asMap());
    }

    @RequestMapping(value = "/rest/save", method = RequestMethod.POST)
    @Override
    public ResultInfo save(User user) {
        if (!StringUtils.isEmpty(user.getId())) {
            //根据id查询原有用户信息
            User old = ds.find(User.class).field("id").equal(user.getId()).get();
            setValue(old, user);
            ResultInfo info = doUpdate(old);
            if (!springUtils.getMessage(UPDATE_NONE).equals(info.getInfo())) {
                return info;
            }
        } else {
            return VoFactory.newResultInfo(ResultInfo.NONE, springUtils.getMessage(UPDATE_NONE));
        }
        return VoFactory.newResultInfo(ResultInfo.SUCCESS, springUtils.getMessage(UPDATE_SUCCESS));
    }

    private void setValue(User old, User nu) {
        old.setPassword(nu.getPassword());
        old.setName(nu.getName());
        old.setSex(nu.getSex());
        old.setTelephone(nu.getTelephone());
//        old.setMobilePhone(nu.getMobilePhone());
//        old.setEmail(nu.getEmail());
        old.setAddress(nu.getAddress());
        //其他参数页面上没有，不变
    }

    @Override
    protected String getBaseName() {
        return "user";
    }
}
